package com.lengxf.design;

import java.util.Stack;

public class InstructionHandler {

    private AbstractNode node;


    public void handle(String instruction) {
        Stack<AbstractNode> stack = new Stack<>();
        String[] words = instruction.split(" ");

        for (int i = 0; i < words.length; i++) {
            if (words[i].equals("and")) {
                AbstractNode left = stack.pop();
                String word1 = words[++i];
                AbstractNode direction = new DirectionNode(word1);
                String word2 = words[++i];
                AbstractNode action = new ActionNode(word2);
                String word3 = words[++i];
                AbstractNode distance = new DistanceNode(word3);
                AbstractNode right = new SentenceNode(direction, action, distance);
                stack.push(new AndNode(left, right));
            } else {
                String word1 = words[i];
                AbstractNode direction = new DirectionNode(word1);
                String word2 = words[++i];
                AbstractNode action = new ActionNode(word2);
                String word3 = words[++i];
                AbstractNode distance = new DistanceNode(word3);
                AbstractNode left = new SentenceNode(direction, action, distance);
                stack.push(left);
            }
        }
        this.node = stack.pop();
    }

    public String outPut() {
        return node.interpret();
    }

}
